﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.SessionState;
using NetWing.Model;//系统所有的model 都在这个命名空间里，这个还是比较有好处的。
using NetWing.BPM.Core;
using NetWing.Common;
using Omu.ValueInjecter;
using NetWing.Common.Data;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using NetWing.Common.Data.SqlServer;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Linq;

namespace NetWing.BPM.Admin.mjfinancemain.ashx
{
    /// <summary>
    /// mjfinance 的摘要说明
    /// </summary>
    public class mjfinance : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //context.Response.Write("Hello World");
            var main = HttpContext.Current.Request["main"];//得到主表json数据
            var detail = HttpContext.Current.Request["detail"];//得到明细表json数据
            int mainInsertedId = 0;//（主表公用）主表插入的ID
            string edNumber = common.mjcommon.getedNumber("CW");//得到此次财务订单号，原来是浏览器给，现在从系统获取

            if (string.IsNullOrEmpty(main) || string.IsNullOrEmpty(detail))
            {
                context.Response.Write("{\"status\":0,\"msg\":\"失败！主表或子表信息为空！\"}");
                context.Response.End();//输出结束
            }

            #region 主表处理
            var mainobj = JSONhelper.ConvertToObject<MJFinanceMainModel>(main);//根据模型把json数据转化为obj
            MJFinanceMainModel mainModel = new MJFinanceMainModel();//初始化模型
            mainModel.InjectFrom(mainobj);//把obj插入模型
            mainModel.add_time = DateTime.Now;
            mainModel.up_time = DateTime.Now;
            mainModel.edNumber = edNumber;
            mainModel.depid= int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
            mainModel.dep = SysVisitor.Instance.cookiesCurrentDepName;
            mainModel.ownner= int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
            mainModel.operate = SysVisitor.Instance.cookiesUserName;//操作人
            mainModel.operateid = int.Parse(SysVisitor.Instance.cookiesUserId);//操作人ID
            mainModel.accountb = mainModel.account;//收付款账号ID
            mainModel.accountidb = mainModel.accountid;
            mainModel.note = mainModel.note+";财务记账单";
            mainModel.shifub = mainModel.payment;//实付因为只有一个账号所以这里就这样

            #endregion



            #region 子表明细表处理
            JArray detailArr = JArray.Parse(detail);//把明细表转化为数组
            var k = detailArr[0].ToString();
            #endregion

            SqlTransaction tran = SqlHelper.BeginTransaction(SqlEasy.connString);//取得一个事务
            try
            {
                mainInsertedId = DbUtils.tranInsert(mainModel, tran);//往主表插入一条
                //循环明细表
                for (int i = 0; i < detailArr.Count; i++)//有几条就执行几次
                {
                    var detailobj = JSONhelper.ConvertToObject<MJFinanceDetailModel>(detailArr[i].ToString());//根据模型把明细表转化为obj
                    MJFinanceDetailModel detailModel = new MJFinanceDetailModel();//初始化明细表模型
                    detailModel.InjectFrom(detailobj);//把obj插入模型
                    detailModel.edNumber = edNumber;//订单号赋值
                    detailModel.financeId = mainInsertedId;//父子表关联
                    detailModel.add_time = DateTime.Now;
                    detailModel.up_time = DateTime.Now;
                    detailModel.ownner= int.Parse(SysVisitor.Instance.cookiesUserId);//数据所有者ID
                    detailModel.depid= int.Parse(SysVisitor.Instance.cookiesUserDepId);//数据权限部门ID
                    detailModel.contact = mainModel.contact;
                    detailModel.contactid = mainModel.contactid;
                    detailModel.username = mainModel.unit;
         
                    //detailModel.dep= SysVisitor.Instance.cookiesCurrentDepName;

                    DbUtils.tranInsert(detailModel, tran);//执行写入明细表

                }
                //循环明细表
                //事务的方法更新银行余额
                int c = DbUtils.tranExecuteNonQuery("update MJBankAccount set accountBalance=accountBalance+" + mainModel.payment + " where KeyId=" + mainModel.accountid + "", tran);


                tran.Commit();//提交执行事务
                context.Response.Write("{\"status\":1,\"msg\":\"提交成功！\"}");
            }
            catch (Exception e)
            {
                tran.Rollback();//错误！事务回滚！
                context.Response.Write("{\"status\":0,\"msg\":\"" + e.ToString() + "\"}");
                throw;
            }




        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}